package com.lams.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlSqlCodeFactroy {
	private static final String XMLFILEPATH = "/WEB-INF/config/SQL_CODE.xml";
	private static Map<String, SqlBean> beanMap = new HashMap<String, SqlBean>();
	private static Logger logger =Logger.getLogger(XmlSqlCodeFactroy.class);
//	static{
//		if(beanMap == null) initBeanMap();
//	}
	public static SqlBean getSqlBeanByCode(String sqlcode){
		SqlBean bean = beanMap.get(sqlcode);
		if(bean == null) initBeanMap(ServletActionContext.getServletContext());
		return beanMap.get(sqlcode);
	}
	public static void initBeanMap(ServletContext context){
	//	beanMap = new HashMap<String, SqlBean>();
		beanMap.clear();
		File file = new File(context.getRealPath(XMLFILEPATH));
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(file);
			Element root = document.getRootElement();
			for(Iterator<Element> iterator = root.elementIterator(); iterator.hasNext();){
				Element sql = iterator.next();
				String sqlcode = sql.attributeValue("SQL_CODE");
//				logger.info("SQLCODE:"+sqlcode);
				SqlBean bean = new SqlBean();
				bean.setSqlcode(sqlcode);
				for(Iterator<Element> sqlIterator = sql.elementIterator();sqlIterator.hasNext();){
					Element item = sqlIterator.next();
					String value = item.getTextTrim();
//					logger.info(item.getName()+":"+value + ";"+ item.getTextTrim());
					if(item.getName().equals("CONTENT")){
						bean.setContent(value);
					}
					if(item.getName().equals("FIELDS")){
						String[] fields = {};
						if(!"".equals(value))fields = value.split(",");
						bean.setFields(fields);
					}
					if(item.getName().equals("REMARK")) {
						bean.setRemark(value);
					}
				}
				beanMap.put(sqlcode, bean);
			}
			logger.info("SQL_CODES:"+beanMap.keySet());
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}
